/* @refresh reload */
import { TonConnectUI } from 'src/ton-connect-ui';
import { THEME } from 'src/models';
import { SendTransactionRequest, TonConnect } from '@tonconnect/sdk';
// import Koa from "koa";
// import koaRouter from "koa-router"
// import bodyParser from 'koa-bodyparser'; // koa post 内容解析
// import Koa from 'koa';
// import koaRouter from 'koa-router';
// import bodyParser from "koa-bodyparser";
import { accountParse } from "src/utils/accountUtils"
import { getTransactionHistory } from "src/utils/historyUtils"
// import { testWebSocket } from "src/joinService"
// let hash = accountParse("UQAxp7JMc1uNTO8mLdnmwzCLmqIRUTZhNvDsKHJIUedg_zaa");
// console.log("112112121",hash)
// testWebSocket()

// getTransactionHistory().then(res => {
//     console.log(res)
// })
async function dev(): Promise<void> {
    let orderId = document.location.pathname.substring(1)
    //截取末尾订单号
    console.log("订单号:",orderId)
    if(orderId.length>5){
        //发送订单消息
        console.log("发送订单消息")
    }

    const connector = new TonConnect({
        manifestUrl: 'https://bk.yyge.net/CDN/tonconnect-manifest.json'
    });

    const tonConnectUI = new TonConnectUI({
        connector,
        buttonRootId: 'button-root',
        actionsConfiguration: {
            modals: ['error'],
            notifications: ['before'],
            twaReturnUrl: 'https://google.com'
        },
        uiPreferences: {
            theme: THEME.LIGHT,
            borderRadius: 'm'
        },
        language: 'en',
        restoreConnection: true,
        walletsListConfiguration: {
            includeWallets: []
        }
    });
    // console.log(121,)



    let wallets = tonConnectUI.getWallets();
    wallets.then(res=>{
        console.log(res)
    })

    //打开UI界面
    await tonConnectUI.openModal();
    setTimeout(async () => {
        //获取当前钱包的连接状态
        const currentModalState = tonConnectUI.modalState;
        //如果当前连接状态是关闭状态则进行连接
        console.log("当前连接状态:",currentModalState)
        if(!currentModalState.closeReason){
          //await tonConnectUI.openSingleWalletModal('wallet');
        }
    },500)

    /*tonConnectUI.setConnectRequestParameters({ state: 'loading' });

    setInterval(() => {
        tonConnectUI.setConnectRequestParameters({
            state: 'ready',
            value: { tonProof: 'tonProofPayload' + Math.random().toString() }
        });
    }, 3000);*/

    tonConnectUI.onStatusChange(wallet => {
        document.getElementById('content')!.textContent = wallet ? JSON.stringify(wallet) : wallet;
    });

    //转账事件
    document.getElementById('send-tx')!.onclick = () => {
        //目标账户:需要转换
        let hash = accountParse("UQAq6vGp6jDK25PFhTuzTWP_ZYy37CqoxhKlwGD4kMW1dLNS")
        let num=1000000 * 1
        const defaultTx: SendTransactionRequest = {
            validUntil: Math.round(Date.now() / 1000) + 1000,
            //TON汇率  1000000=0.001 TON
            //手续费按照 0.001 算
            messages: [
                {
                    address: hash,
                    amount: num+"",
                    // payload:'123456789',
                }
            ]
        };

        let promise =  tonConnectUI.sendTransaction(defaultTx, {
            modals: 'all',
            notifications: 'all'
        });

        promise.then(result=>{
            console.log(result)
        }).then(error=>{
            console.log("报错啦",error)
        })
    };

    //  tc.connectWallet();
    /*
    setTimeout(() => {
        tc.uiOptions = {
            language: 'ru',
            theme: THEME.DARK
        };
    }, 0);
    setTimeout(() => {
        widgetController.openActionsModal('confirm-transaction');
    }, 500);
    setTimeout(() => {
        widgetController.openActionsModal('transaction-sent');
    }, 1000);

    setTimeout(() => {
        widgetController.openActionsModal('transaction-canceled');
    }, 1500);*/
    /*try {
        await tc.connectWallet();

        const defaultTx = {
            validUntil: Date.now() + 1000000,
            messages: [
                {
                    address: '0:412410771DA82CBA306A55FA9E0D43C9D245E38133CB58F1457DFB8D5CD8892F',
                    amount: '20000000'
                },
                {
                    address: '0:E69F10CC84877ABF539F83F879291E5CA169451BA7BCE91A37A5CED3AB8080D3',
                    amount: '60000000'
                }
            ]
        };

        const uiConfig = {
            showModalBefore: true,
            showSuccessModalAfter: true,
            showErrorModalAfter: true
        };

        await tc.sendTransaction(defaultTx, uiConfig);
    } catch (e) {
        console.log(e);
    }*/
}

function init(){

    // const app = new Koa();
    // console.log(app)
    // const router = new koaRouter()
    // const app = new Koa();
    // const router = new Router();


    // 使用 koa-bodyparser 中间件来解析 POST 请求中的数据
    // app.use(bodyParser());
    //
    // // 中间件，处理请求日志
    // app.use(async (ctx:any, next:any) => {
    //   console.log(`${ctx.method} ${ctx.url}`);
    //   await next();
    // });
    //
    // // Get请求
    // router.get('/api/hello', async (ctx:any) => {
    //   ctx.body = 'Hello, world!6666';
    // });
    //
    // // POST请求
    // router.post('/api/doPost', async (ctx:any) => {
    //     console.log(ctx.request.body)
    //   ctx.body = 'Hello, world post!';
    // });
    //
    // // 注册路由
    // app.use(router.routes());
    // app.use(router.allowedMethods());
    //
    // // 启动服务
    // const port = process.env.PORT || 1122;
    // app.listen(port, () => {
    //   console.log(`Server is running on port ${port}`);
    // });
}
// setTimeout(init, 500);
setTimeout(dev, 1500);
